//
//  ChooseDetailViewController.m
//  ErWa
//
//  Created by 李雪 on 16/3/10.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "ChooseDetailViewController.h"
#import "NewNestHeader.h"
#import <TencentOpenAPI/QQApiInterfaceObject.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <QuartzCore/QuartzCore.h>
#import <TencentOpenAPI/TencentOAuth.h>
@interface ChooseDetailViewController ()

@property (nonatomic, strong) UIScrollView *scrollview;
@property (nonatomic, strong) NSMutableArray *imgArr;/**< 图片数组 */
@property (nonatomic, strong) UIBarButtonItem *collectionButton;/**<  */
@property (nonatomic, strong) UIButton *likeButton;
@property (nonatomic, strong)TencentOAuth *tencentOAuth;/**< qq */

@end

@implementation ChooseDetailViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSLog(@"SK == %s",__FUNCTION__);
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 视图创建
    [self createSubviews];

    #pragma mark - 夜间模式
    BOOL model = [AccountManager sharedInstance].isNight;
    if (model == YES) {
        self.view.backgroundColor = [UIColor grayColor];
        self.scrollview.backgroundColor = [UIColor grayColor];
    } else {
        self.view.backgroundColor = [UIColor clearColor];
    }

    
}

/// 视图创建
- (void)createSubviews
{
    // 图片数组
    self.imgArr = _modal.imageUrl;
    
    //scrollview
    self.scrollview = [[UIScrollView alloc] initWithFrame:SVIEW_B];
    self.scrollview.contentSize = CGSizeMake(SVIEW_FW, SVIEW_FH / 3 * (_imgArr.count + 1) );
    [self.view addSubview:_scrollview];
    
    // 上方的文章标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 10)];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = _modal.name;
    titleLabel.font = [UIFont systemFontOfSize:20];
    [self.scrollview addSubview:titleLabel];
    
    // 房屋类型视图
    ChooseDetailCell *houseTypeView = [[ChooseDetailCell alloc] initWithFrame:CGRectMake(10, titleLabel.frame.origin.y + titleLabel.frame.size.height + 10, (self.view.frame.size.width - 20) / 4 , self.view.frame.size.height / 6)];
    houseTypeView.titleLabel.text = _modal.houseType;
    houseTypeView.imgview.image = [UIImage imageNamed:@"C19"];
    [self.scrollview addSubview:houseTypeView];
    
    //房屋风格视图
    ChooseDetailCell *styleView = [[ChooseDetailCell alloc] initWithFrame:CGRectMake(houseTypeView.frame.origin.x + houseTypeView.frame.size.width , houseTypeView.frame.origin.y, houseTypeView.frame.size.width, houseTypeView.frame.size.height)];
    styleView.titleLabel.text = _modal.style;
    styleView.imgview.image = [UIImage imageNamed:@"C18"];
    [self.scrollview addSubview:styleView];
    
    //房屋面积视图
    ChooseDetailCell *spaceView = [[ChooseDetailCell alloc] initWithFrame:CGRectMake(styleView.frame.origin.x + styleView.frame.size.width, houseTypeView.frame.origin.y, houseTypeView.frame.size.width, houseTypeView.frame.size.height)];
    spaceView.titleLabel.text = _modal.space;
    spaceView.imgview.image = [UIImage imageNamed:@"C22"];
    [self.scrollview addSubview:spaceView];
    
    //价格视图
    ChooseDetailCell *priceView = [[ChooseDetailCell alloc] initWithFrame:CGRectMake(spaceView.frame.origin.x + spaceView.frame.size.width, houseTypeView.frame.origin.y, houseTypeView.frame.size.width, houseTypeView.frame.size.height)];
    priceView.titleLabel.text = _modal.price;
    priceView.imgview.image = [UIImage imageNamed:@"C21"];
    [self.scrollview addSubview:priceView];
    
    // 用于存放所有图片的数组
    
    for (NSInteger i = 0; i < _imgArr.count; i++) {
        UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(10, SVIEW_FH / 3 * (i + 1) + 10, SVIEW_FW - 20, SVIEW_FH / 3)];
        imgview.layer.cornerRadius = 5;
        imgview.clipsToBounds = YES;
        [imgview sd_setImageWithURL:[NSURL URLWithString:_imgArr[i]] placeholderImage:[UIImage imageNamed:@"placeHolder.jpg"]];
        [self.scrollview addSubview:imgview];
    }
    
    // 右上角的分享按钮
    UIBarButtonItem *shareBtton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fenxiang"] style:UIBarButtonItemStylePlain target:self action:@selector(share:)];
    
    self.likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _likeButton.frame = CGRectMake(SCREEN_W / 7 * 6, SCREEN_H / 15, 25, 25);
    
    [_likeButton setImage:[UIImage imageNamed:@"kongaixin@2x"] forState:UIControlStateNormal];
    [_likeButton setImage:[UIImage imageNamed:@"hongaixin@2x"] forState:UIControlStateSelected];
    [_likeButton addTarget:self action:@selector(collect:) forControlEvents:UIControlEventTouchUpInside];
    
    self.collectionButton = [[UIBarButtonItem alloc] initWithCustomView:_likeButton];
    
    self.navigationItem.rightBarButtonItems = @[shareBtton, _collectionButton];
    
}

// 收藏按钮的实现
- (void)collect: (UIButton *)sender
{
    // 判断是不是 已经登录
    //    BOOL login = [[NSUserDefaults standardUserDefaults] boolForKey:@"didLogin"];
    //    if (login) {
    // 如果登录了
    NSLog(@"%@", NSHomeDirectory());
    // 创建关于精选的文件夹
    NSString *BoutiquePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"Boutique"];
    //创建精选文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:BoutiquePath withIntermediateDirectories:YES attributes:nil error:nil];
    //        // 获取当前登录人的用户名
    //        NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    //        NSString *userPath = [BoutiquePath stringByAppendingPathComponent:userName];
    //        // 创建一个当前登录的人的文件夹
    //        [[NSFileManager defaultManager] createDirectoryAtPath:userPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    // 先获取当前保存数据的数组
    NSMutableArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:[BoutiquePath stringByAppendingPathComponent:@"Boutique.plist"]];
    // 判断数组是不是存在
    if (arr) {
        NSLog(@"当前精选数组存在");
        // 如果存在就遍历 看是不是已经收藏过
        for (ChoiceModel *m in arr) {
            //判断
            if ([m.name isEqualToString:_modal.name]) {
                NSLog(@"已经收藏");
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该精选内容已经收藏过!" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [alert show];
                [alert dismissWithClickedButtonIndex:0 animated:YES];
                
                // 结束
                return;
            }
        }// 不包含就把它加到数组里面并显示已经收藏成功
        [arr addObject:_modal];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功啦~" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        
        // 改变收藏按钮的背景图片
        self.likeButton.selected = YES;
        
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
    } else {
        // 如果数组不存在 就创建一个新的数组 把modal加到数组里面 并显示收藏成功
        NSLog(@"创建新数组并收藏");
        // 初始化数组
        arr = [NSMutableArray array];
        [arr addObject:_modal];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功啦~" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        
        // 改变收藏按钮的背景图片
        self.likeButton.selected = YES;
        
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        
    }
    
    // 将数组写到本地
    [NSKeyedArchiver archiveRootObject:arr toFile:[BoutiquePath stringByAppendingPathComponent:@"Boutique.plist"]];
    //
    //    } else {
    //        // 进入登录界面
    //        LoginVC *loginVC = [LoginVC new];
    //        UINavigationController *loginNavi = [[UINavigationController alloc] initWithRootViewController:loginVC];
    //        [self.navigationController presentViewController:loginNavi animated:YES completion:^{
    //
    //        }];
    //    }
    
    
}

// 分享按钮的实现
- (void)share:(UIButton *)sender
{
    QQApiNewsObject *newsObj = [QQApiNewsObject objectWithURL:[NSURL URLWithString:@"www.baidu.com"] title:@"dddddddd" description:nil previewImageURL:[NSURL URLWithString:@"www.baidu.com"] targetContentType:QQApiURLTargetTypeNews];
    
    
    
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
    //将内容分享到qq
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    //将内容分享到qzone
    //    QQApiSendResultCode sent = [QQApiInterface SendReqToQZone:req];
    
    [self handleSendResult:sent];
}

- (void)handleSendResult:(QQApiSendResultCode)sendResult
{
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
                                    UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
                        [msgbox show];
            

            
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送参数错误" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"API接口不支持" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        case EQQAPISENDFAILD:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            
            break;
        }
        default:
        {
            break;
        }
    }
}

-(void)tencentDidLogin
{
    //    _labelTitle.text = @"登录完成";
    
    
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length])
    {
        //  记录登录用户的OpenID、Token以及过期时间
        //        _labelAccessToken.text = _tencentOAuth.accessToken;
        NSLog(@"%@", _tencentOAuth.accessToken);
        [_tencentOAuth accessToken];
        [_tencentOAuth openId];
        [_tencentOAuth expirationDate];
        
        [_tencentOAuth getUserInfo];
        
    }
    else
    {
        //        _labelAccessToken.text = @"登录不成功 没有获取accesstoken";
        NSLog(@"登陆不成功, 没有获取accesstoken");
    }
}

-(void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled)
    {
        //        _labelTitle.text = @"用户取消登录";
        NSLog(@"用户取消登陆");
    }
    else
    {
        //        _labelTitle.text = @"登录失败";
        NSLog(@"登陆失败");
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
